﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;
using log4net;
using System.Reflection;
using GrailTechnology.AutoTags.DataType;
using GrailTechnology.OpenCalais;
using Newtonsoft.Json;
using umbraco.cms.businesslogic.web;
using System.Net;

namespace GrailTechnology.AutoTags.Library
{
    public class Base
    {
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public static string GetTags(int id)
        {
            HttpRequest post = HttpContext.Current.Request;
            Document d = new Document(id);

            log.Debug("Getting tags for node: " + id);

            var keys = new List<string>();

            foreach (string key in post.Form)
            {
                if ((!key.StartsWith("_")) && (!key.ToLower().Contains("tag") ))
                {
                    keys.Add(key);
                    log.Debug("form: " + key + " - " + post.Form[key]);
                }
            }

            string text = Helper.Instance.GetFormProperties(post.Form, keys); // To get data from form rather than node properties
            log.Debug("Using text: " + text);


            HttpContext.Current.Response.ContentType = "application/json";

            OpenCalaisService s = new OpenCalaisService(Config.Instance.OpenCalaisApiKey);
            if (Config.Instance.ProxyDomain.Length > 0)
            {
                s.Proxy = new WebProxy
                {
                    Credentials = new NetworkCredential(
                        Config.Instance.ProxyUsername,
                        Config.Instance.ProxyPassword,
                        Config.Instance.ProxyDomain)
                };
            }

            try
            {
                string[] tags = s.GenerateTags(text);
                Array.Sort(tags);
                var result = new {
                                 items = tags,
                                 autoAdd = Config.Instance.SelectTagsAutomatically                              
                             };

                return JsonConvert.SerializeObject(result);
            }
            catch (Exception ex)
            {
                log.Fatal(ex);
                return JsonConvert.SerializeObject(new { error = ex.Message });
            }
        }
    }
}